<script setup lang="ts">
import type { EChartsOption } from 'echarts';

import { onMounted, onUnmounted, ref, watch } from 'vue';

import * as echarts from 'echarts';

const props = defineProps<{
  chartData: {
    chartData?: number[];
    indicators?: Array<{
      max: number;
      name: string;
    }>;
  };
}>();

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

const getOptions = (): EChartsOption => ({
  backgroundColor: 'transparent',
  radar: {
    indicator: props.chartData.indicators,
    shape: 'polygon',
    splitNumber: 4,
    axisName: {
      color: '#8AB5E9',
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(138, 181, 233, 0.3)',
      },
    },
    splitArea: {
      show: false,
    },
    axisLine: {
      lineStyle: {
        color: 'rgba(138, 181, 233, 0.3)',
      },
    },
  },
  series: [
    {
      name: '各类型书籍阅读情况',
      type: 'radar',
      data: [
        {
          value: props.chartData.chartData,
          name: '人数',
          itemStyle: {
            color: '#FF6B3D',
          },
          lineStyle: {
            color: '#FF6B3D',
          },
          areaStyle: {
            color: 'rgba(255, 107, 61, 0.3)',
          },
        },
      ],
    },
  ],
});

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(chartRef.value);
  chart.setOption(getOptions());
};

// 监听数据变化
watch(
  () => props.chartData,
  () => {
    chart?.setOption(getOptions());
  },
  { deep: true },
);

// 监听指标变化
watch(
  () => props.chartData.indicators,
  () => {
    chart?.setOption(getOptions());
  },
  { deep: true },
);

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chart?.dispose();
});
</script>

<template>
  <div ref="chartRef" :style="{ width: '100%', height: '270px' }"></div>
</template>
